const model = require('../model');

const fs = require('fs');

const jwt = require('jsonwebtoken');

const util = require('util');

const verify = util.promisify(jwt.verify);// 解密

const secret = require('../secret').secret;

const path = require('path');

const extname = path.extname;

const crypto = require('crypto');

let User = model.User,
    Photo = model.Photo,
    Comment = model.Comment;

const APIError = require('../rest').APIError;

module.exports = {
    'GET /api/test': async (ctx, next) => {
        const token = ctx.header.authorization; // 获取jwt
        if (!token) {
            throw new APIError('token: false', 'token false');
        } else {
            payload = await verify(token.split(' ')[1], secret);
            ctx.rest({
                payload
            })
        }
    },
    'POST /api/regin': async (ctx, next) => {
        if (ctx.request.body.password !== ctx.request.body.password_repeat) {
            throw new APIError('password: not same', 'passwords are not same');
        }
        let md5 = crypto.createHash('md5');

        let newUser = await User.create({
            email: ctx.request.body.email,
            passwd: md5.update(ctx.request.body.password).digest('base64'),
            name: ctx.request.body.username,
            isAdmin: false,
            like: 0
        });
        newUser.passwd = undefined;

        let userToken = {
            name: newUser.email
        };
        const token = jwt.sign(userToken, secret, {expiresIn: '2h'});  //token签名 有效期为2小时

        ctx.rest({
            newUser,
            token
        });
    },
    'POST /api/login': async (ctx, next) => {
        let md5 = crypto.createHash('md5');

        let user = await User.findOne({
            attributes: { exclude: ['passwd'] },
            where: {
                email: ctx.request.body.email,
                passwd: md5.update(ctx.request.body.password).digest('base64')
            }
        });

        let userToken = {
            name: user.email
        };
        const token = jwt.sign(userToken, secret, {expiresIn: '2h'});  //token签名 有效期为2小时

        ctx.rest({
            user,
            token
        })
    },
    'GET /api/userInfo': async (ctx, next) => {
        const userId = ctx.request.body.userId;
        let user = undefined;
        if (userId) {
            user = await User.findOne({
                attributes: { exclude: ['passwd', 'email'] },
                where: {
                    email: payload.email
                }
            });
        } else {
            const token = ctx.header.authorization;  // 获取jwt
            let payload = await verify(token.split(' ')[1], secret);// // 解密，获取payload
            user = await User.findOne({
                attributes: { exclude: ['passwd'] },
                where: {
                    email: payload.email
                }
            });
        }
        ctx.rest({
            user
        })
    },
    'GET /api/allUserInfos': async (ctx, next) => {
        const token = ctx.header.authorization;  // 获取jwt
        let payload = await verify(token.split(' ')[1], secret);// // 解密，获取payload
        let user = await User.findOne({
            where: {
                email: payload.email
            }
        });
        if (user.isAdmin) {
            let allUsers = await User.findAll({
                attributes: { exclude: ['passwd'] }
            });
            ctx.rest({
                allUsers
            })
        } else {
            throw new APIError('Auth: not_admin', 'You are not a admin');
        }

    },
    'POST /api/uploadPhoto': async (ctx, next) => {
        // const file = ctx.request.body.files.file;
        // const reader = fs.createReadStream(file.path);
        // const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
        // reader.pipe(stream);
        // console.log('uploading %s -> %s', file.name, stream.path);

        // const token = ctx.header.authorization; // 获取jwt
        // let payload;
        // if (token) {
        //     payload = await verify(token.split(' ')[1], secret);// // 解密，获取payload
        // } else {
        //
        // }

        // console.log('body', JSON.stringify(ctx.request.body));
        // console.log('fields', JSON.stringify(ctx.request.body.fields));
        // console.log('files', ctx.request.body.fields.files);
        // console.log('files type', typeof ctx.request.body.fields.files);
        // const files = ctx.request.body.fields.files;

        let newPhotos = [];
        console.log(JSON.stringify(ctx.request.body));
        const files = ctx.request.body.files.fileArr;
        for (let value of files) {
            console.log(value);
        }
        for (let value of files) {
            let reader = fs.createReadStream(value.path);
            let stream = fs.createWriteStream(path.join("download", Math.random().toString() + value.name));
            reader.pipe(stream);
            console.log('uploading %s -> %s', value.name, stream.path);

            let photo = await Photo.create({
                userId: ctx.request.body.fields.userId,
                path: stream.path.replace('download\\', ''),
                like: 0
            });
            newPhotos.push(photo);
        }
        ctx.rest({
            newPhotos
        });
    },
    'GET /api/downloadPhoto/:fileName': async (ctx, next) => {
        function stat(file) {
            return new Promise(function(resolve, reject) {
                fs.stat(file, function(err, stat) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(stat);
                    }
                });
            });
        }
        let fileName = ctx.params.fileName;
        let fpath = path.join('download', fileName);
        const fstat = await stat(fpath);

        if (fstat.isFile()) {
            ctx.type = extname(fpath);
            console.log(ctx.type);
            ctx.body = fs.createReadStream(fpath);
        }
    },
    'GET /api/allphotos': async (ctx, next) => {
        let allPhotos = await Photo.findAll();
        console.log(allPhotos);
        ctx.rest({
            allPhotos
        });
    },
    'POST /api/postComment': async (ctx, next) => {
        let comment = await Comment.create({
            text: ctx.request.body.commentText,
            like: 0,
            photoId: ctx.request.body.photoId,
            userId: ctx.request.body.userId
        });
        ctx.rest({
            comment
        })
    },
    'POST /api/getComments': async (ctx, next) => {
        let comments = await Comment.findAll({
            where: {
                photoId: ctx.request.body.photoId
            }
        });
        ctx.rest({
            comments
        })
    }
};
